#rem
	Copyright (c) 2012 Peter J Rigby
	
	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

#END

Import timelinefx.gameobject

Class tlVehicle Extends tlComponent
	
	Field velocity:tlVector2
	Field mass:Float = 10
	Field heading:tlVector2
	Field side:tlVector2
	Field maxspeed:Float = 5
	Field maxforce:Float = 1
	Field maxturnrate:Float = 1
	
	Field steeringbehaviour:tlSteeringBehaviours
	
	Method New(name:string)
		Name = name
	End
	
	Method Init()
		steeringbehaviour = New tlSteeringBehaviours(Self)
		velocity = New tlVector2()
		heading = New tlVector2()
		side = New tlVector2()
	End
	
	Method Update()
		Local steeringforce:tlVector2 = steeringbehaviour.Calculate()
		Local acceleration:tlVector2 = steeringforce.Divide(mass)
		velocity.AddVectorSelf(acceleration)
		velocity.Truncate(maxspeed)
		Parent.MoveVector(velocity)
		heading = velocity.GetNormalised()
		side = heading.Normal()
	End
	

End

Class tlSteeringBehaviours

	Field vehicle:tlVehicle
	Field target:tlVector2

	Method New(vehicle:tlVehicle)
		Self.vehicle = vehicle
	End
	
	Method Seek:tlVector2(target:tlVector2)
		Local desiredv:tlVector2 = target.SubtractVector(vehicle.parent.WorldVector()).GetNormalised().Scale(vehicle.maxspeed)
		Return desiredv.SubtractVector(vehicle.velocity)
	End
	
	Method Calculate:tlVector2()
		If Target
			Return Seek(Target)
		EndIf
	End
	
	Method Target:Void(target:tlVector2) Property
		Self.target = target
	End
	
	Method Target:tlVector2() Property
		Return target
	End
	
End